Skip to main content

第 4 章:使用 Template 系統

只需事先定義變數和模板 (Templates),即可用它動態產生遠端的 Shell Scripts、設定檔 (Configure) 等。換句話說,我們可以用一份 template 來產生開發 (Development)、測試 (Test) 和正式環境 (Production) 等不同環境設定。

建立 template 檔案
$ vi hello_world.txt.j2
Hello "{{ dynamic_word }}"
  • 由於 Ansible 是藉由 Jinja2 來實作 template 系統,所以請使用 .j2 的副檔名
  • 上面 "{{ dynamic_word }}" 代表在此 template 裡使用了名為 dynamic_word 的變數
建立 playbook,並加入變數
vi template_demo.yml
---
- name: Play the template module
hosts: localhost
vars:
dynamic_word: "World"
tasks:
- name: generation the hello_world.txt file
template:
src: hello_world.txt.j2
dest: /tmp/hello_world.txt
- name: show file context
command: cat /tmp/hello_world.txt
register: result

- name: print stdout
debug:
msg: "{{ result.stdout_lines }}"
# vim:ft=ansible :
  • 在第 5 行,我們幫 dynamic_word 變數設了一個預設值 World
  • 在第 8 行,使用 template module,並指定檔案的來源 (src) 和目的地 (dest)
  • 之後的 2 個 tasks 則是把 template module 產生出來的檔案給印出來
  • 執行 playbook。
    • 直接執行 playbook。

       ansible-playbook template_demo.yml
    • 透過 e 參數將 dynamic_word 覆寫成 ansible。

       ansible-playbook template_demo.yml -e "dynamic_word=ansible"
    • 透過 e 參數將 dynamic_word 覆寫成 Day14。

       ansible-playbook template_demo.yml -e "dynamic_word=Day14"

怎麼讓 Playbooks 切換不同的環境

  1. 在 Playbooks 裡除了用 vars 來宣告變數以外,還可以用 [vars_files](http://docs.ansible.com/ansible/playbooks_variables.html#variable-file-separation) 來 include 其它的變數檔案,如下例的第 7 行。
vi template_demo2.yml
- name: Play the template module
hosts: localhost
vars:
env: "development"

vars_files:
- vars/{{ env }}.yml

tasks:
- name: generation the hello_world.txt file
template:
src: hello_world.txt.j2
dest: /tmp/hello_world.txt

- name: show file context
command: cat /tmp/hello_world.txt
register: result

- name: print stdout
debug:
msg: "{{ result.stdout_lines }}"

# vim:ft=ansible :
  1. 建立 vars/development.ymlvars/test.yml 和 vars/production.yml 檔案,接下來將依不同的環境 include 不同的變數檔案 (vars files),這樣就可以用同一份 playbook 切換環境了

    • Development

       vi vars/development.yml
      dynamic_word: "development"
    • Test

       vi vars/test.yml
      dynamic_word: "test"
    • Production

       vi vars/production.yml
      dynamic_word: "production"
  2. 執行 playbook,並透過 e 切換各個環境。

    ansible-playbook template_demo2.yml -e “env=test”
  3. 若要在大型的 Playbook 裡切環境,建議使用較進階的 group_vars 和 host_vars